<?php

namespace App\Admin\Controllers;

use App\Models\Game;
use App\Models\ModelList;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;

use Illuminate\Support\Facades\DB;
use Encore\Admin\Widgets\Table;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\MessageBag;
use App\Models\ModelVersion;

class ModelController extends AdminController
{
    /**
     * {@inheritdoc}
     */
    protected function title()
    {
        //return trans('admin.administrator');
        return '模型';
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new ModelList());
        $grid->model()->orderBy('id', 'desc');

        $isAdmin = Admin::user()->isAdministrator();

        $uid = Admin::user()->id;
        if(!$isAdmin){
            $grid->model()->where('uid', $uid);
        }

        $grid->column('id', 'ID')->sortable();

        $grid->column('name', '模型名称')->expand(function ($model) {
            $id = $this->id;
            $arr = ModelVersion::select('id','version','status','train_file','add_date')->where('model_id',$id)->orderby('id','desc')->limit(10)->get()->toArray();

            //0：待训练1：训练中2：训练成功3：训练失败4：模型文件格式错误
            $arrName = ['待训练','训练中','训练成功','训练失败','模型文件格式错误','模型转换中'];
            foreach($arr as $k=>$v){
                $arr[$k]['status'] = $arrName[$arr[$k]['status']];

                $arr[$k]['train_file'] = 'http://'.request()->getHost().'/storage/'.$arr[$k]['train_file'];
            }

            return new Table(['ID', '版本','状态','下载','发布时间'], $arr);
        });

        $grid->column('version', '最新版本');
        $grid->column('desc', '简介')->sortable();

        $grid->column('train_file','下载')->downloadable()->display(function($file_path,$column) {
            if($file_path){
                return $column->qrcode();
            }else{
                return '';
            }
        });

        $grid->column('created_at', trans('admin.created_at'));
        $grid->column('updated_at', trans('admin.updated_at'));



        $grid->filter(function($filter){
            $filter->disableIdFilter();//去掉默认的id过滤器
            $filter->like('name', '模型名称');
        });

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();//隐藏查看
            $actions->disableDelete();
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(ModelList::findOrFail($id));
        $show->field('id', 'ID');
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form()
    {
        $form = new Form(new ModelList());

        $arr = request()->route()->parameters();
        $isAdmin = Admin::user()->isAdministrator();

        //验证编辑内容是否属于自己
        $uid = Admin::user()->id;
        if(!$isAdmin && isset($arr['list'])){
            $list = ModelList::where('uid',$uid)->where('id', $arr['list'])->count();

            if(!$list){
                abort(404);
            }
        }

        $form->display('id', 'ID');
        $form->text('name', '模型名称')->rules('required')
            ->creationRules(['required', "unique:v_model"],['unique'=>'该名称已经存在~'])
            ->updateRules(['required', "unique:v_model,name,{{id}}"],['unique'=>'该名称已经存在~']);

        $form->text('version', '版本')->rules('required');
        $form->file('file','文件')
            //->disk('oss')
            ->move('file/data/'.date('Ym'))
            ->uniqueName()
            ->retainable(true)
            ->rules('required');

        $form->textarea('desc', '简介')->rules('required');

        $form->display('created_at', trans('admin.created_at'));
        $form->display('updated_at', trans('admin.updated_at'));

        $uid = Admin::user()->id;
        $form->hidden('uid')->value($uid);

        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
            $tools->disableView();
            $tools->disableList();
        });

        $form->saving(function (Form $form) {
            $id = $form->model()->id;
            $nowV = $form->model()->version;
            $v = $form->version;
            $file = $form->file;

            if($id && ($file || $nowV != $v)){
                //验证版本号是否重复
                $check = ModelVersion::where('model_id',$id)->where('version',$v)->first();
                if($check){
                    $error = new MessageBag([
                        'title'   => '添加失败',
                        'message' => '该版本已存在，请重置版本号~',
                    ]);

                    return back()->with(compact('error'));
                }

                //验证当前文件是否存在
                if(!$file && $v){
                    $error = new MessageBag([
                        'title'   => '添加失败',
                        'message' => '版本号要和模型同时更新~',
                    ]);

                    return back()->with(compact('error'));
                }
            }

            if(isset($_FILES['file']['name']) && $_FILES['file']['name'] && pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION) !== 'cnp'){
                $error = new MessageBag([
                    'title'   => '保存失败',
                    'message' => '文件扩展名必须是cnp',
                ]);

                return back()->with(compact('error'));
            }

            if(isset($_FILES['fileUrl']['size']) && $_FILES['fileUrl']['size'] && $_FILES['fileUrl']['size'] > 1000*1024*1024){
                $error = new MessageBag([
                    'title'   => '保存失败',
                    'message' => '文件不能超过1000M',
                ]);

                return back()->with(compact('error'));
            }
        });

        $form->saved(function (Form $form) {
            $id = $form->model()->id;
            $v = $form->model()->version;
            $file = $form->model()->file;
            $info = $form->model()->info;
            $desc = $form->model()->desc;

            //验证当前文件是否存在
            $log = ModelVersion::where('model_id',$id)->where('file',$file)->first();
            if(!$log){
                $arr = [
                    'model_id' => $id,
                    'version' => $v,
                    'file' => $file,
                    'desc' => $desc,
                    'info' => $info,
                    'add_date' => date('Y-m-d H:i:s')
                ];

                $logId = ModelVersion::insertGetId($arr);

                ModelVersion::where('id',$logId)->update(['train'=>date('Ymd').'/'.$id.'_'.$logId.'/']);
            }

            return true;
        });

        return $form;
    }
}
